import 'dart:math';
import 'dart:ui';

import 'package:appinio_video_player/appinio_video_player.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';

// import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_file_downloader/flutter_file_downloader.dart';
// import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:like_button/like_button.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:player_js/player_js.dart';
import 'package:provider/provider.dart';

import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/controller/imageDetailVideoController.dart';
import 'package:qianyi/entity/home/Comment.dart';
import 'package:qianyi/network/http_manager.dart';

import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/view_model/home/comment_view_model.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:quds_ui_kit/screens/quds_bottom_sheet_container.dart';


import 'package:chewie/chewie.dart';
// import 'package:video_js/video_js.dart';
// import 'package:webview_flutter/webview_flutter.dart';

import '../../controller/VideoPlayerController.dart';
import '../../controller/imageDetailUserController.dart';
import '../../entity/home/ImageVideoDetailEntity.dart';
import '../../entity/mine/User.dart';
import '../../network/http_config.dart';
import '../../network/http_entity.dart';
import '../../state/token.dart';
import '../../utils/DialogUtils.dart';
import '../../utils/common_dialog.dart';
import '../../view_model/home/video_player_model.dart';
import '../widget/custom_refresh.dart';
import 'MyCustomController.dart';
import 'operation_page.dart';

class ImageVideoDetail extends StatefulWidget {

  ImageVideoDetail( );

  @override
  _ImageVideoDetail createState() => _ImageVideoDetail();
}

class _ImageVideoDetail extends State<ImageVideoDetail>  with SingleTickerProviderStateMixin{

  HomeTabController homeTabController = Get.find();
  ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
  CustomVideoPlayerController? _customVideoPlayerController = null;
  late VideoPlayerModel videoPlayerModel;
  ChewieController? chewieController = null;
  VideoPlayerController? videoPlayerController = null;
  TokenController tokenController = Get.find<TokenController>();
  TextEditingController textcontroller = TextEditingController();
  int currentIndex = 0;
  bool isMp4 = false;
  bool isFllow = false;
  List<Map<String,dynamic>> twoLevelManager = <Map<String,dynamic>>[];
  CommentViewModel? commentViewModel;
  ImageDetailUserController imageDetailUserController = Get.find();
  final FocusNode focusNode = FocusNode();
  double _expandedHeight = 380.0;
  double _targetExpandedHeight = 480.0;

  @override
  void dispose() {
    imageDetailVideoController.disposeVideoPlayers();
    videoPlayerModel.disposeVideoPlayers();
    // _chewieController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    isFllowUser();
    initVideoPlayer();
    // TODO: implement initState
    // 监听 ImageVideoDetailEntity 的变化

  }
  isFllowUser(){
    ImageVideoDetailEntity imageVideoDetail = imageDetailVideoController.imageVideoDetailEntity.value.first;

    Map<String,dynamic> params = {
      "uid": tokenController.uid,
      "fid": imageVideoDetail.userId
    };
    HttpEntity httpEntity;
    HttpManager.getInstance().request(url: '/platform/follow/isFollow',method: Method.get,params: params).then((res)=>{
      httpEntity = res as HttpEntity,
      this.isFllow = httpEntity.oriData['data']

    });

  }
  initVideoPlayer() async {

    ImageVideoDetailEntity imageVideoDetail = imageDetailVideoController.imageVideoDetailEntity.value.first;
    // imageDetailVideoController.initVideoPlayer1(imageVideoDetail.imgsUrl!);


    setState(() {


    });

  }

  @override
  Widget build(BuildContext context) {
    ImageVideoDetailEntity imageVideoDetail = imageDetailVideoController.imageVideoDetailEntity.value.first;
    return GestureDetector(
      onTap: (){
        focusNode.unfocus();
      },
      child: ChangeNotifierProvider(
          create: (BuildContext context) =>  VideoPlayerModel(imageVideoDetail.imgsUrl!,true),
          child: Consumer<VideoPlayerModel>(builder: (context, viewModel, child) {
            videoPlayerModel = viewModel;
            computeHeight(videoPlayerModel);
            List<VideoPlayerController> list = viewModel.videoPlayerControllers;
            return  SafeArea(

              child: Scaffold(
                resizeToAvoidBottomInset: true,

                body: NestedScrollView(
                  headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                    return <Widget>[

                      TweenAnimationBuilder(
                        tween: Tween<double>(begin: _expandedHeight, end: _targetExpandedHeight),
                        duration: Duration(milliseconds: 300),
                        builder: (BuildContext context, double value, Widget? child) {

                          return SliverAppBar(
                            actions: [
                              IconButton(onPressed: (){
                                showQudsModalBottomSheet(

                                    context,
                                        (c) => Column(
                                      children: [
                                        // ListTile(
                                        //   leading: Icon(Icons.edit),
                                        //   title: Text('转入专辑'),
                                        //   onTap: (){
                                        //
                                        //     // Get.toNamed("/edit/editPage");
                                        //   },
                                        // ),
                                        ListTile(
                                          leading: Icon(Icons.delete),
                                          title: Text('删除图片'),
                                          onTap: (){
                                            DialogUtils.showConfirmDialog(
                                                context, "是否确认删除", "落子无悔删除后不可恢复").then((
                                                result) async {

                                              if (result!) {
                                                HudUtil.showBeautiful(context);
                                                List<String> params = [];
                                                params.add(imageVideoDetail.id!);

                                                HttpEntity h = await HttpManager.getInstance().request(url: "/platform/imgDetail/deleteImgs/${tokenController.uid}",method: Method.post,listParams: params) as HttpEntity;
                                                Get.toNamed("/home");

                                                HudUtil.dismiss();
                                                // uploadVideo();

                                              }
                                            }

                                            );
                                          },
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.policy),
                                          title: Text('社区公约'),
                                          onTap: (){},
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.save),
                                          title: Text('保存视频'),
                                          onTap: () async {
                                            HudUtil.showBeautiful(context);

                                            final directory = Theme.of(context).platform == TargetPlatform.android
                                                ? await getExternalStorageDirectory()
                                                : await getApplicationSupportDirectory();
                                            ;
//You can download a single file
                                            FileDownloader.downloadFile(
                                                url: imageVideoDetail!.imgsUrl![0],
                                                name: "THE FILE NAME AFTER DOWNLOADING",//(optional)
                                                subPath: directory!.path!,//(optional)
                                                onProgress: (fileName, double progress) {
                                                  print('FILE fileName HAS PROGRESS $progress!');
                                                },
                                                onDownloadCompleted: (String path) {
                                                  HudUtil.dismiss();
                                                  print('FILE DOWNLOADED TO PATH: $path');
                                                },
                                                onDownloadError: (String error) {
                                                  print('DOWNLOAD ERROR: $error');
                                                });
                                           // HudUtil.dismiss();

                                          },
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.qr_code),
                                          title: Text('QQ'),
                                          onTap: (){},
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.wechat),
                                          title: Text('微信'),
                                          onTap: (){},
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.camera_alt),
                                          title: Text('朋友圈'),
                                          onTap: (){},
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.language),
                                          title: Text('新浪微博'),
                                          onTap: (){},
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.link),
                                          title: Text('复制链接'),
                                          onTap: (){

                                            String url = 'https://www.lihuo.fun/#/pages/main/main?mid=${imageVideoDetail.id}';
                                            Clipboard.setData(ClipboardData(text: url)).then((_) {
                                              final snackBar = SnackBar(content: Text('链接已复制到剪贴板'));
                                              ScaffoldMessenger.of(context).showSnackBar(snackBar);
                                              Navigator.pop(context);
                                            });
                                          },
                                        ),
                                        ListTile(
                                          leading: Icon(Icons.cancel),
                                          title: Text('取消'),
                                          onTap: (){},
                                        ),
                                      ],
                                    ),
                                    titleText: '操作');
                              }, icon: Icon(Icons.share_outlined))
                            ],
                            centerTitle: true,
                            title: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children:[
                                    GestureDetector(
                                        onTap: () async {
                                          HudUtil.showBeautiful(context);
                                          if(imageDetailUserController.user.length > 0) {
                                            imageDetailUserController.user.clear();

                                          }

                                          Map<String,dynamic> param = {
                                            "uid": imageVideoDetail.userId
                                          };
                                          HttpEntity httpEntity = await HttpManager.getInstance().request(url: '/platform/user/getUserInfo',method: Method.get,params: param) as HttpEntity;
                                          User user = User.fromJson(httpEntity.getOriData()['data']);
                                          imageDetailUserController.user.add(user);
                                          imageDetailUserController.userId = imageVideoDetail.userId!;
                                          HudUtil.dismiss();
                                          Get.toNamed("/user/otherUserScreen");
                                        },
                                        child:  ClipOval(

                                          child:   FancyShimmerImage(imageUrl: imageVideoDetail.avatar!,width: 30,height: 30,),

                                        )
                                    )
                                    ,

                                    Padding(padding: EdgeInsets.only(left: 10),child: Text("${imageVideoDetail.username}",style: TextStyle(
                                        fontSize: 15,fontWeight: FontWeight.w400
                                    ),),),],
                                ),
                                GestureDetector(
                                  child: Container(
                                    width: 70,
                                    height: 30,
                                    padding: EdgeInsets.all(0.0), // 内边距
                                    decoration: BoxDecoration(
                                      border: Border.all(
                                        color: WcaoTheme.primary, // 边框颜色
                                        width: 0.5, // 边框宽度
                                      ),
                                      borderRadius: BorderRadius.circular(14.0), // 圆角大小
                                    ),
                                    child: ConstrainedBox(
                                      constraints: BoxConstraints(

                                      ),
                                      child: Center(
                                        child: Text(
                                          isFllow? "已关注":"关注",
                                          textAlign: TextAlign.center, // 文本居中
                                          style: TextStyle(fontSize: 14.7,color: WcaoTheme.primary), // 文本样式
                                        ),
                                      ),
                                    ),
                                  ),
                                  onTap: (){

                                    if(tokenController.uid == imageVideoDetail.userId) {

                                      return;
                                    }
                                    HudUtil.showBeautiful(context);
                                    Map<String,dynamic> params = {
                                      "uid": tokenController.uid,
                                      "fid": imageVideoDetail.userId
                                    };
                                    HttpEntity httpEntity;
                                    HttpManager.getInstance().request(url: '/platform/follow/followUser',method: Method.post,params: params).then((res)=>{
                                      httpEntity = res as HttpEntity,

                                      HudUtil.dismiss()
                                    });
                                    setState(() {
                                      this.isFllow = !this.isFllow;
                                    });
                                  },
                                )


                              ],
                            ),
                            flexibleSpace: FlexibleSpaceBar(
                              background: createSwiper(imageVideoDetail, list,videoPlayerModel),
                            ),
                            expandedHeight: value,
                            collapsedHeight: 240,
                            pinned: true,
                          );
                        },
                        onEnd: () {
                          // setState(() {
                          // _expandedHeight = _targetExpandedHeight;
                          // });
                        },
                      ),

                    ];
                  },
                  body: Stack(
                      children: [

                        ChangeNotifierProvider(
                            create: (BuildContext context) => CommentViewModel(vsync: this),
                            builder: (BuildContext context, Widget? child) {
                              commentViewModel = Provider.of<CommentViewModel>(context);

                              return CustomRefresh(

                                enablePullDown: true,
                                enablePullUp: true,


                                onRefresh: () {
                                  commentViewModel!.onRefresh();
                                },
                                onLoading: (){
                                  commentViewModel!.onLoading();
                                },
                                controller: commentViewModel!.refreshController,
                                child: SingleChildScrollView(
                                  physics: NeverScrollableScrollPhysics(),
                                  child: Padding(
                                    padding: EdgeInsets.only(top: 16,left: 8,right: 8,),
                                    child: Column(
                                      children: [



                                        Card(
                                          margin:EdgeInsets.all(0),
                                          child: Column(
                                            children: [
                                              Container(
                                                width: MediaQuery.of(context).size.width,
                                                child: Wrap(
                                                  children: [
                                                    Text('${imageVideoDetail.content}',

                                                      style: TextStyle(
                                                        // fontWeight: FontWeight.w400,
                                                        fontSize: 16,height: 1.5,),),

                                                  ],
                                                ),
                                              )



                                              ,
                                              Row(
                                                children: [

                                                  Text('${imageVideoDetail.time} | ${imageVideoDetail.viewCount} 浏览',style: TextStyle(
                                                    color: Colors.grey,
                                                    fontWeight: FontWeight.w300,
                                                    fontSize: 12,
                                                    height: 1.5,


                                                  ),),
                                                  Text("${imageVideoDetail.status==0?'含有色情':''}",style: TextStyle(
                                                  color: WcaoTheme.primary,
                                                    fontWeight: FontWeight.w300,
                                                    fontSize: 12,
                                                    height: 1.5,


                                                  ))
                                                ],
                                              ),
                                              Container(
                                                height: 0.33,
                                                margin: EdgeInsets.only(bottom: 0),
                                                color: Colors.grey.withOpacity(.2),
                                              ),
                                              Row(
                                                children: [
                                                  Text('所属专辑',style: TextStyle(

                                                    // fontWeight: FontWeight.w400,
                                                      fontSize: 16,height: 2.1),),
                                                ],
                                              ),
                                              Container(
                                                height: 130,
                                                color: WcaoTheme.bgColor, // 假设WcaoTheme.bgColor已经定义
                                                child: GestureDetector(
                                                  onTap: () async {
                                                    homeTabController.albumDetailId = imageVideoDetail.album!.id!;
                                                    videoPlayerModel.pasueVideoPlayer(0);
                                                    Get.toNamed("/mine/albumScreen");
                                                  },
                                                  child: Stack(
                                                    children: <Widget>[
                                                      // 第一个元素占据一半的宽度以及整个容器的高度
                                                      Positioned(
                                                        left: 0,
                                                        top: 0,
                                                        right: null,
                                                        bottom: 0,
                                                        width: MediaQuery.of(context).size.width / 2, // 宽度为容器宽度的一半
                                                        child: Container(
                                                          height: 130, // 高度与容器相同
                                                          // color: Colors.blue,
                                                          child:const Image(
                                                            image: AssetImage("assets/kg.jpg"),
                                                            fit: BoxFit.fitWidth, // 根据需要选择 BoxFit
                                                          )
                                                          // FancyShimmerImage(
                                                          //   imageUrl: "${imageVideoDetail.album!.cover!}",
                                                          // )
                                                          ,
                                                        ),
                                                      ),
                                                      // 第二个元素占据一半的宽度以及容器下半部分的高度
                                                      Positioned(
                                                        right: 0,
                                                        // top: 65, // 从容器顶部下移65像素，占据下半部分

                                                        bottom: null,
                                                        width: MediaQuery.of(context).size.width / 2-20, // 宽度为容器宽度的四分之一
                                                        height: 65, // 高度为容器高度的一半
                                                        child: Container(
                                                          // color: Colors.red,
                                                          child: Center(child: Text('${imageVideoDetail.album!.name!}')),
                                                        ),
                                                      ),
                                                      // 第三个元素占据一半的宽度以及容器下半部分的高度
                                                      Positioned(
                                                        right:0, // 从容器左边开始四分之一的宽度
                                                        top: 65, // 从容器顶部下移65像素，占据下半部分

                                                        bottom: null,
                                                        width: MediaQuery.of(context).size.width / 2-20, // 宽度为容器宽度的四分之一
                                                        height: 65, // 高度为容器高度的一半
                                                        child: Container(
                                                          // color: Colors.green,
                                                          child: Center(child: Text('${imageVideoDetail.album!.imgCount!}个内容|${imageVideoDetail.agreeCount}人收藏')),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              )

                                            ],
                                          )
                                          ,
                                        ),
                                        SizedBox(
                                            width: MediaQuery.of(context).size.width-20,
                                            child: Wrap(
                                              spacing: 8.0, // 设置子组件之间的水平间距
                                              runSpacing: 4.0, // 设置子组件之间的垂直间距
                                              children: imageVideoDetail.tagList!.map((tag) =>
                                                  TextButton(
                                                    onPressed: () {
                                                      // 处理按钮点击事件
                                                      homeTabController.tagDetailId = tag.id;
                                                      Get.toNamed("/mine/TagsScreen");
                                                    },
                                                    child: Text("${tag.name}"),
                                                    style: ButtonStyle(
                                                      // 设置TextButton的样式
                                                      foregroundColor: MaterialStateProperty.all<Color>(WcaoTheme.base), // 文字颜色
                                                      backgroundColor: MaterialStateProperty.all<Color>(WcaoTheme.bgColor), // 背景颜色
                                                      overlayColor: MaterialStateProperty.resolveWith<Color?>(
                                                            (Set<MaterialState> states) {
                                                          if (states.contains(MaterialState.hovered)) {
                                                            return Colors.grey.withOpacity(0.3);
                                                          }
                                                          if (states.contains(MaterialState.focused) || states.contains(MaterialState.pressed)) {
                                                            return Colors.grey.withOpacity(0.3);
                                                          }
                                                          return null; // Defer to the widget's default.
                                                        },
                                                      ),
                                                    ),
                                                  )
                                              ).toList(),
                                            )
                                        ),
                                        Container(
                                          height: 0.33,
                                          margin: EdgeInsets.only(bottom: 0),
                                          color: Colors.grey.withOpacity(.2),
                                        ),
                                        Row(
                                          children: [

                                            Text("评论",style: TextStyle(fontSize: 16,height: 1.5)),
                                          ],
                                        ),

                                        Consumer<CommentViewModel>(
                                            builder: (context, commentViewModel, child) {
                                              // Use VideoPlayerModel to build your UI
                                              return commentViewModel.datas.length<=0?
                                              Image.asset("assets/nomore.png"):
                                              Column(
                                                children:  commentViewModel.datas.map((item) {
                                                  Comment comment = item;

                                                  // 假设每个item是一个字符串或者可以转换为字符串的对象
                                                  // 如果item是一个Map或其他复杂对象，您可能需要先提取出需要显示的值
                                                  return Card(
                                                    margin: EdgeInsets.all(0),
                                                    child: Column(
                                                      children: [
                                                        Row(
                                                          children: [
                                                            GestureDetector(
                                                                onTap: () async {
                                                                  HudUtil.showBeautiful(context);
                                                                  if(imageDetailUserController.user.length > 0) {
                                                                    imageDetailUserController.user.clear();

                                                                  }

                                                                  Map<String,dynamic> param = {
                                                                    "uid": comment.uid
                                                                  };
                                                                  HttpEntity httpEntity = await HttpManager.getInstance().request(url: '/platform/user/getUserInfo',method: Method.get,params: param) as HttpEntity;
                                                                  User user = User.fromJson(httpEntity.getOriData()['data']);
                                                                  imageDetailUserController.user.add(user);
                                                                  imageDetailUserController.userId = comment.uid!;
                                                                  HudUtil.dismiss();
                                                                  Get.toNamed("/user/otherUserScreen");
                                                                },
                                                                child: ClipOval(

                                                                  child: FancyShimmerImage(imageUrl: comment.avatar!,width: 40,height: 40,),

                                                                ),
                                                            )
                                                            ,
                                                            Container(
                                                              margin: EdgeInsets.only(left: 5), // 向左添加10像素的margin
                                                              child: Text("${comment.username}",style: TextStyle(

                                                                  color: WcaoTheme.indexBootBarColor,
                                                                  fontWeight: FontWeight.w400
                                                              ),),
                                                            ),

                                                          ],
                                                        ),
                                                        Material(
                                                          color: Colors.transparent, // 设置为透明，以显示波纹效果
                                                          child: InkWell(
                                                            onTap: () {
                                                              DialogDelegate.showBottomPop(context, "回复评论",comment,commentViewModel);
                                                            },
                                                            splashColor: WcaoTheme.primary.withAlpha(30), // 波纹颜色
                                                            highlightColor: Colors.blue.withAlpha(50), // 点击高亮颜色
                                                            child: Container(
                                                              width: MediaQuery.of(context).size.width,
                                                              margin: EdgeInsets.only(left: 45),
                                                              padding: EdgeInsets.all(2), // 增加内边距，使点击区域更大
                                                              child: Text(
                                                                comment.content,
                                                                style: TextStyle(
                                                                  // fontWeight: FontWeight.w400,
                                                                  fontSize: 16, // 假设这是你的基本字体大小
                                                                ),
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                        SizedBox(
                                                            height: 25,
                                                            child: Stack(
                                                              children: [
                                                                Positioned(top:0,child:  Container(

                                                                  margin: EdgeInsets.only(left: 45), // 向左添加10像素的margin
                                                                  child:  Text(
                                                                      '${DateTime.fromMillisecondsSinceEpoch(comment.createDate)}',
                                                                      style: TextStyle(
                                                                          height: 1.5,
                                                                          fontSize: WcaoTheme.fsSm,
                                                                          color: WcaoTheme.indexBootBarColor,
                                                                          fontWeight: FontWeight.w300
                                                                      )
                                                                  ),
                                                                )),

                                                                Positioned(
                                                                  right: 0,

                                                                  child: GestureDetector(
                                                                    onTap: () async{
                                                                      HudUtil.showBeautiful(context);
                                                                      await commentViewModel.agreeone(comment);
                                                                      HudUtil.dismiss();
                                                                    },
                                                                    child: Row(
                                                                      children: [
                                                                        comment.isAgree?Icon(
                                                                          Icons.favorite,size: 14,
                                                                        ):
                                                                        Icon(

                                                                          Icons.favorite_outline_sharp, size: 14,
                                                                        ),
                                                                        Text('${comment.count}'),

                                                                      ],
                                                                    ),
                                                                  ),
                                                                ),


                                                              ],
                                                            )
                                                        ),

                                                        Column(
                                                          children: comment.childrenComments.map((ce) {
                                                            return Padding(padding: EdgeInsets.only(left: 50),child: Column(
                                                              children: [
                                                                Row(
                                                                  children: [

                                                                    ClipOval(

                                                                      child: FancyShimmerImage(imageUrl: ce.avatar!,width: 40,height: 40,),

                                                                    ),
                                                                    Container(
                                                                      margin: EdgeInsets.only(left: 5), // 向左添加10像素的margin
                                                                      child: Text("${ce.uid==imageVideoDetail.userId?'作者:':''}${ce.username}",style: TextStyle(

                                                                          color: WcaoTheme.indexBootBarColor,
                                                                          fontWeight: FontWeight.w400
                                                                      ),),
                                                                    ),

                                                                  ],
                                                                ),
                                                                GestureDetector(
                                                                    onTap: () async{
                                                                      DialogDelegate.showBottomPop2(context, 'title', ce, commentViewModel,comment.id);
                                                                    },
                                                                    child: Container(
                                                                      width: MediaQuery.of(context).size.width,
                                                                      margin: EdgeInsets.only(left: 45), // 向左添加10像素的margin
                                                                      child: RichText(
                                                                        text: TextSpan(
                                                                          style: TextStyle(
                                                                            // fontWeight: FontWeight.w400,
                                                                            fontSize: WcaoTheme.fsBase, // 确保WcaoTheme.fsBase已经定义
                                                                          ),
                                                                          children: <TextSpan>[
                                                                            TextSpan(
                                                                              text: '回复: ',
                                                                              style: TextStyle(color: WcaoTheme.base
                                                                              ), // 设置“回复: ”为灰色
                                                                            ),
                                                                            TextSpan(
                                                                              text: '${ce.replyName}',
                                                                              style: TextStyle( color: WcaoTheme.indexBootBarColor,
                                                                                  // fontWeight: FontWeight.w400,
                                                                                  fontSize: WcaoTheme.fsBase),
                                                                            ),
                                                                            TextSpan(
                                                                                text: '${ce.content}',
                                                                                style: TextStyle(color: WcaoTheme.base,)// 剩余文本保持默认样式
                                                                            ),
                                                                          ],
                                                                        ),
                                                                      ),
                                                                    )
                                                                )
                                                                ,

                                                                SizedBox(
                                                                    height: 25,
                                                                    child: Stack(
                                                                      children: [
                                                                        Positioned(top:0,child:  Container(

                                                                          margin: EdgeInsets.only(left: 45), // 向左添加10像素的margin
                                                                          child:  Text(
                                                                              '${DateTime.fromMillisecondsSinceEpoch(ce.createDate)}',
                                                                              style: TextStyle(
                                                                                  height: 1.5,
                                                                                  fontSize: WcaoTheme.fsSm,
                                                                                  color: WcaoTheme.indexBootBarColor,
                                                                                  fontWeight: FontWeight.w300
                                                                              )
                                                                          ),
                                                                        )),

                                                                        Positioned(
                                                                          right: 0,

                                                                          child: GestureDetector(
                                                                            onTap:() {
                                                                              commentViewModel.twoLevelLike(ce);
                                                                            },
                                                                            child: Row(
                                                                              children: [
                                                                                ce.isAgree?Icon(

                                                                                  Icons.favorite, size: 14,
                                                                                ): Icon(

                                                                                  Icons.favorite_outline_sharp, size: 14,
                                                                                ),
                                                                                Text('${ce.count}'),

                                                                              ],
                                                                            ),
                                                                          ),
                                                                        ),


                                                                      ],
                                                                    )
                                                                ),

                                                              ],
                                                            ));

                                                          }).toList(),
                                                        ),
                                                        twoLevelComment(comment,commentViewModel)
                                                      ],
                                                    ),
                                                  );
                                                }).toList(),
                                              );
                                              ; // Assuming you use VideoPlayerModel here
                                            }
                                        )


                                      ],
                                    ),
                                  ),
                                ),
                              );
                            }
                        )
                        ,

                        Positioned(bottom:0,
                          child: IntrinsicHeight(
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  // color: Colors.grey, // 容器的背景颜色
                                  borderRadius: BorderRadius.circular(0), // 圆角的大小
                                ),

                                margin: EdgeInsets.only(left: 8,right: 8),
                                width: MediaQuery.of(context).size.width-20,
                                // height: 40,
                                child: Row(
                                  children: [
                                    SizedBox(
                                      width: MediaQuery.of(context).size.width/2,
                                      child: TextField(
                                        focusNode: focusNode,
                                        maxLines: null, // 允许无限行数
                                        expands: true, // 允许TextField展开以填充可用空间
                                        controller: textcontroller,
                                        decoration: InputDecoration(
                                          hintText: '留下你的足迹',
                                          border: InputBorder.none,

                                        ),
                                      ),
                                    ),
                                    GestureDetector(
                                        onTap: () async{
                                          if(textcontroller.text.length<=0) return ;

                                          HudUtil.showBeautiful(context);

                                          String uid =  await tokenController.getUid();
                                          Map<String,dynamic> params = {
                                            "content":textcontroller.text,
                                            "uid":uid,
                                            "mid":imageVideoDetail.id,
                                            "pid":0,
                                            "replyId":0,
                                            "replyUid":0,
                                            "level":1
                                          };
                                          HttpManager.getInstance().request(url: '/platform/comment/addComment',method: Method.post,params: params).then((value) => {
                                            HudUtil.dismiss(),
                                            textcontroller.clear(),
                                            commentViewModel!.onRefresh()
                                          });
                                        },
                                        child:  Text("发送")
                                    )
                                    ,
                                    IconButton(
                                        alignment: Alignment.centerRight,
                                        onPressed: (){

                                          if(tokenController.uid == imageVideoDetail.userId!){
                                            HudUtil.showFail("自己不能添加");
                                            return;
                                          }
                                          homeTabController.setAddAlbumImageId = imageVideoDetail.id!;
                                          Get.toNamed("/mine/dongtai/addAlbumViewToMe");
                                        }, icon: Icon(Icons.star_border)),

                                    Text("${imageVideoDetail.collectionCount}"),

                                    IconButton(onPressed: () async {
                                      HudUtil.showBeautiful(context);


                                      String uid = await tokenController.getUid();
                                      Map<String,dynamic> param = {
                                        "uid":uid,
                                        "type":1,
                                        "agreeCollectId":imageVideoDetail.id,
                                        "agreeCollectUid":imageVideoDetail.userId,
                                        "itemId": imageVideoDetail.id
                                      };
                                      if(!imageDetailVideoController.isAgree.value){
                                        HttpEntity h = await HttpManager.getInstance().request(url: '/platform/agreeCollect/agree',method: Method.post,params: param) as HttpEntity;
                                        imageDetailVideoController.isAgree.value = true;
                                        int ti = int.parse(imageVideoDetail!.agreeCount!);
                                        ti = ti+1;
                                        imageVideoDetail!.agreeCount = ti.toString();
                                        ;
                                      } else {
                                        HttpEntity h = await HttpManager.getInstance().request(url: '/platform/agreeCollect/cancelAgree',method: Method.post,params: param) as HttpEntity;
                                        imageDetailVideoController.isAgree.value = false;
                                        int ti = int.parse(imageVideoDetail!.agreeCount!);
                                        ti = ti-1;
                                        imageVideoDetail!.agreeCount = ti.toString();
                                      }
                                      setState(() {

                                      });
                                      HudUtil.dismiss();


                                    }, icon:

                                    Obx(
                                            ()=>

                                        imageDetailVideoController.isAgree.value? Icon(Icons.thumb_up,color: WcaoTheme.primary,):Icon(Icons.thumb_up_off_alt)
                                    ),
                                    ),
                                    Text("${imageVideoDetail.agreeCount}"),
                                  ],
                                ),
                              )),
                        ),
                        Positioned(right:0,child:  imageVideoDetail.imgsUrl!.isNotEmpty && imageVideoDetail.imgsUrl!.any((url) => url.toLowerCase().contains('.mp4'))||imageVideoDetail.imgsUrl!.any((url) => url.toLowerCase().contains('.m3u8'))?
                        Text("${videoPlayerModel.currentIndex+1}/${videoPlayerModel.videoPlayerControllers.length}",style: TextStyle(),):Text("${currentIndex+1}/${imageVideoDetail.imgsUrl!.length}",style: TextStyle(),),
                        ),
                      ]
                  ),
                ),
              )

              ,

            )
            ;
          })),
    )
      ;
  }


  createSwiper(ImageVideoDetailEntity imageVideoDetail, List<VideoPlayerController> list,VideoPlayerModel videoPlayerModel) {

    bool containsMp4 = imageVideoDetail.imgsUrl!.isNotEmpty && imageVideoDetail.imgsUrl!.any((url) => url.toLowerCase().contains('.mp4')) || imageVideoDetail.imgsUrl!.any((url) => url.toLowerCase().contains('.m3u8'));
    this.isMp4 = containsMp4;

    return containsMp4 ?
    Swiper(

      autoplay: false,
      loop: false,
      onIndexChanged: (index) {
        videoPlayerModel.pasueVideoPlayer(index);
      },

      itemBuilder: (BuildContext context,int index) {
      String videoUrl = imageVideoDetail.imgsUrl![0];

        return Container(
          decoration: BoxDecoration(

            boxShadow: [
              BoxShadow(
                  blurRadius: 40,
                  offset: Offset(2, 4),
                  color: Colors.transparent
              )
            ],
          ),
          child:
          // kIsWeb?
          // VideoPlayer(list[index])
          // VideoJsWidget(
          //   videoJsController: _videoJsController,
          //   height: MediaQuery.of(context).size.width / 2.5,
          //   width: MediaQuery.of(context).size.width / 1.5,
          // )
          // // VideoPlayer(list[index]!)
          //       :

          CustomVideoPlayer(

              customVideoPlayerController: CustomVideoPlayerController(

                customVideoPlayerSettings: CustomVideoPlayerSettings(

                    placeholderWidget: FancyShimmerImage(
                      imageUrl: '${imageVideoDetail.cover}',

                    ),

                    settingsButtonAvailable: false,
                    showFullscreenButton: true,
                    customAspectRatio: list[index]!.value!.aspectRatio,
                    durationAfterControlsFadeOut:const Duration(seconds: 2),
                    controlBarDecoration: BoxDecoration(
                      color: Color.fromRGBO(0, 0, 0, 0),
                      borderRadius: BorderRadius.all(
                        Radius.circular(10),
                      ),
                    )
                ),
                context: context,
                videoPlayerController: list[index]!,

              )
          )
          ,
        );
      },
      itemCount: imageVideoDetail.imgsUrl!.length,
    ):
    Swiper(
      autoplay: true,
      autoplayDelay: 6000, // 设置自动播放的间隔时间为 6 秒
      duration: 200, // 设置动画持续时间为 500 毫秒
      onIndexChanged: (index) {
        currentIndex = index;
        setState(() {

        });
      },
      itemCount: imageVideoDetail.imgsUrl!.length,
      itemBuilder: (context,index) {

        return FancyShimmerImage(
            boxFit: BoxFit.fitWidth,
            imageUrl: imageVideoDetail.imgsUrl![index]
        );
      },
    );
  }

  computeHeight(VideoPlayerModel videoPlayerModel) {
    double width = videoPlayerModel.videoPlayerControllers.first.value.size.width;
    double height = MediaQuery.of(context).size.height;
    double aspect = videoPlayerModel.videoPlayerControllers.first.value.aspectRatio;

    // double d =  videoPlayerModel.videoPlayerControllers.first.value.aspectRatio.ceil() > 16/9?355:height-40;
    double d =  videoPlayerModel.videoPlayerControllers.first.value.aspectRatio.ceil() > 16/9?450:height-40;

    if(aspect == 1) d = 450;
    if(!isMp4) d = 450;
    if(d > 350) {

    }
    this._targetExpandedHeight = d;

    return d;
  }

  twoLevelComment(Comment comment, CommentViewModel commentViewModel) {
    bool b = commentViewModel.twoLevelManager[comment.id]!['hasNext'];


    return GestureDetector(
      onTap: () {
        commentViewModel.requestCommentTwoLevel(comment);
      },
      child: b? Text('点击加载更多'):Text(""),
    );
  }

  // createHtmlVideo(String videoUrl, double width) {
  //
  // String newUrl = videoUrl.replaceAll("http://209.209.10.156:9000","http://192.168.191.139:88/gg");
  //
  // return HtmlVideo(videoUrl:newUrl,width:width);
  //
  //
  // }


}

// class HtmlVideo extends StatefulWidget {
//   final String videoUrl;
//   final double width;
//   const HtmlVideo({super.key, required this.videoUrl, required this.width});
//
//   @override
//   State<HtmlVideo> createState() => _MyWebViewState();
// }
//
// class _MyWebViewState extends State<HtmlVideo> {
//
//   late final WebViewController controller;
//
//   double height = 0;
//   @override
//   void initState() {
//
//     String htmlString = '''
//       <!DOCTYPE html>
//       <html lang="en">
//       <head>
//         <meta charset="UTF-8">
//         <meta name="viewport" content="width=device-width, initial-scale=1.0">
//         <title>Video Player</title>
//       </head>
//       <body oncontextmenu="return false;">
//         <div style="width: 100%;height:400px; text-align: center;">
//         <video id="videoPlayer" controls width="${widget.width}" ></video>
//         </div>
//
//         <script>
//          // 定义获取视频Blob的函数
//       function fetchVideoBlob(url) {
//         // 使用fetch API获取视频
//         fetch(url)
//           .then(response => {
//             // 检查响应状态
//             if (!response.ok) {
//               throw new Error('Network response was not ok');
//             }
//             // 将响应转换为Blob
//             return response.blob();
//           })
//           .then(blob => {
//             // 创建一个Blob URL
//             const videoUrl = URL.createObjectURL(blob);
//             // 设置视频元素的src属性
//             const videoElement = document.getElementById('videoPlayer');
//             videoElement.src = videoUrl;
//             // 可以选择在视频加载后释放Blob URL
//             videoElement.onload = () => {
//               URL.revokeObjectURL(videoUrl);
//             };
//           })
//           .catch(error => {
//             // 处理错误
//             console.error('There was a problem with the fetch operation:', error);
//           });
//       }
//
//       // 在页面加载完毕后调用函数
//       document.addEventListener('DOMContentLoaded', () => {
//         const videoUrl = "${widget.videoUrl}"
//         ;
//         fetchVideoBlob(videoUrl);
//       });
//
//         </script>
//       </body>
//       </html>
//
//       ''';
//     controller = WebViewController()
//       ..setJavaScriptMode(JavaScriptMode.unrestricted)
//       ..loadHtmlString(htmlString);
//
//     super.initState();
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Column(
//       children: [Expanded(child: WebViewWidget(controller: controller))],
//     );
//   }
// }
// HttpManager.getInstance().
// request(url: '/platform/comment/getAllTwoCommentByOneId/${index}/5',params: params,method: Method.get).then((res) => {
// print(res)
// });
